using System.Collections.Generic;
using UnityEngine;

public class TerrainHeight : MonoBehaviour
{
	public GameObject TerrainParent;

	private List<Transform> terrains = new List<Transform>();

	private Rect[] terrainRects;

	public Transform cube;

	private void Awake()
	{
		Transform[] componentsInChildren = TerrainParent.GetComponentsInChildren<Transform>();
		for (int i = 0; i < componentsInChildren.Length; i++)
		{
			Terrain component = componentsInChildren[i].GetComponent<Terrain>();
			if ((bool)component)
			{
				terrains.Add(componentsInChildren[i]);
			}
		}
		terrainRects = new Rect[terrains.Count];
		for (int j = 0; j < terrains.Count; j++)
		{
			Terrain component = terrains[j].GetComponent<Terrain>();
			ref Rect reference = ref terrainRects[j];
			Vector3 position = terrains[j].position;
			reference.x = position.x;
			ref Rect reference2 = ref terrainRects[j];
			Vector3 position2 = terrains[j].position;
			reference2.y = position2.z;
			ref Rect reference3 = ref terrainRects[j];
			Vector3 size = component.terrainData.size;
			reference3.width = size.x;
			ref Rect reference4 = ref terrainRects[j];
			Vector3 size2 = component.terrainData.size;
			reference4.height = size2.z;
		}
	}

	private Terrain GetTerrainTile(Vector3 position)
	{
		for (int i = 0; i < terrains.Count; i++)
		{
			if (terrainRects[i].Contains(new Vector2(position.x, position.z)))
			{
				return terrains[i].GetComponent<Terrain>();
			}
		}
		return null;
	}

	private float GetTerrainHeight(Vector3 position)
	{
		Terrain terrainTile = GetTerrainTile(position);
		if ((bool)terrainTile)
		{
			return terrainTile.SampleHeight(position);
		}
		return -1f;
	}

	private void Update()
	{
		float terrainHeight = GetTerrainHeight(cube.position);
		UnityEngine.Debug.Log("Position: " + cube.position + " height: " + terrainHeight);
	}
}
